package springboot.tools.utils;


import lombok.extern.slf4j.Slf4j;
import springboot.tools.model.MoneyEnum;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据格式类型转换
 */
@Slf4j
public class ConvertUtil {

    /**
     * 单位转换的除数
     */
    protected static final BigDecimal YUAN_DECIMAL = new BigDecimal("1");
    protected static final BigDecimal BW_DECIMAL = new BigDecimal("1000000");
    protected static final BigDecimal KW_DECIMAL = new BigDecimal("10000000");
    protected static final BigDecimal YI_DECIMAL = new BigDecimal("100000000");

    /**
     * 千分符格式
     */
    protected static final DecimalFormat THOUSAND_SEPARATOR_FORMAT = new DecimalFormat("###,###.##");


    /**
     * 格式化,需保证原数据与目标数据变量名称相同(单位转换+空赋值--)
     * 1-元（整数）
     * 2-百万元（整数）
     * 3-千万元（整数）
     * 4-亿元（两位小数）
     */
    public static void formatValue(Object sourceObject, Object targetObject, List<String> percentField, String unit, boolean needThousandSeparator) {
        try {
            //源数据信息
            Class<?> sourceObjClass = sourceObject.getClass();
            Map<String, Field> sourceObjMap = new HashMap<>();
            for (Field field : sourceObjClass.getDeclaredFields()) {
                field.setAccessible(true);
                sourceObjMap.put(field.getName(), field);
            }
            //目标数据信息
            Class<?> targetObjClass = targetObject.getClass();
            for (Field field : targetObjClass.getDeclaredFields()) {
                field.setAccessible(true);
                //获取目标字段名称
                String fieldName = field.getName();
                //寻找匹配字段
                Field sourceField = sourceObjMap.get(fieldName);
                if (sourceField != null) {
                    //能够找到匹配字段，按照类型进行处理
                    sourceField.setAccessible(true);
                    Object fieldValue = sourceField.get(sourceObject);
                    String fieldType = sourceField.getType().getSimpleName();
                    if (fieldValue != null) {
                        if (fieldType.equals("BigDecimal")) {
                            //仅转换BigDecimal类型的数值
                            if (percentField != null && percentField.size() > 0 && percentField.contains(fieldName)) {
                                //转换百分比形式,保留两位小数
                                String percent = NumericUtil.decimalToPercent(new BigDecimal(fieldValue.toString()));
                                field.set(targetObject, percent);
                            } else {
                                //按显示单位转换
                                BigDecimal amount = changeUnit(new BigDecimal(fieldValue.toString()), unit);
                                if (needThousandSeparator) {
                                    //增加千分符
                                    field.set(targetObject, THOUSAND_SEPARATOR_FORMAT.format(amount));
                                } else {
                                    field.set(targetObject, amount);
                                }
                            }
                        }
                    } else {
                        //为空，赋值"--"
                        field.set(targetObject, "--");
                    }
                }
            }
        } catch (Exception e) {
            log.error("格式化异常", e);
        }
    }

    public static String convertToUnit(BigDecimal source, String unit) {
        if (source==null) {
            return "--";
        }
        BigDecimal amount = changeUnit(source, unit);
        //增加千分符
        return THOUSAND_SEPARATOR_FORMAT.format(amount);
    }

    /**
     * 单位转换
     */
    public static BigDecimal changeUnit(BigDecimal amount, String unit) {
        if (MoneyEnum.YUAN.getCode().equals(unit)) {
            //单位：元
            amount = amount.divide(YUAN_DECIMAL, 0, BigDecimal.ROUND_HALF_UP);
        } else if (MoneyEnum.MILLION_YUAN.getCode().equals(unit)) {
            //单位：百万
            amount = amount.divide(BW_DECIMAL, 0, BigDecimal.ROUND_HALF_UP);
        } else if (MoneyEnum.TEN_MILLION_YUAN.getCode().equals(unit)) {
            //单位：千万
            amount = amount.divide(KW_DECIMAL, 0, BigDecimal.ROUND_HALF_UP);
        } else if (MoneyEnum.HUNDRED_MILLION_YUAN.getCode().equals(unit)) {
            //单位：亿
            amount = amount.divide(YI_DECIMAL, 2, BigDecimal.ROUND_HALF_UP);
        }
        return amount;
    }


//    public static void main(String[] args) {
//        CitLossMonitorResponse lossMonitor = new CitLossMonitorResponse();
//        CitReportLossMonitorPO data = new CitReportLossMonitorPO();
//        data.setYearMo("2020-05");
//        data.setLossTotal(new BigDecimal("1232421.23"));
//        formatValue(data, lossMonitor, null, "2", true);
//    }
}
